#!/usr/bin/env python
# -*- coding: utf-8 -*-

import sys
import os
import csv
import traceback
from scpy.logger import get_logger

import pypinyin
from pypinyin import pinyin, lazy_pinyin  # 拼音第三方库

def read_csv_and_find_field(csv_path):
    result = []
    field_index = {}
    with open(csv_path, 'rb') as csvfile:
        csv_reader = csv.reader(csvfile)
        header = csv_reader.next()
        for field_name in header:
            field_index[field_name] = header.index(field_name)
        result.append(header)

        for row in csv_reader:
            result.append(row)

    return field_index, result

def create_pinyin(name):
    name = name.replace('*', '').replace('Ｂ', 'b').lower()
    if not isinstance(name, unicode):
        name = name.decode('utf-8')
    first_letters = pinyin(name, style=pypinyin.FIRST_LETTER)  # style设置取首字母, heteronym启用多音字模式

    for index, fl in enumerate(first_letters):
        if isinstance(fl, list):
            first_letters[index] = ''.join(fl)

    return '_'.join(first_letters).encode('utf-8')  # eg: 四川长虹 ----> s_c_zc_hgj


def write_to_csv(csv_path, result):
    with open(csv_path, 'wb+') as csvfile:
        csv_writer = csv.writer(csvfile)
        csv_writer.writerows(result)


if __name__ == '__main__':
    # ROOT_PATH = os.path.abspath(os.path.join(os.path.dirname(__file__), os.path.pardir))
    csv_path_input = os.path.join(os.path.dirname(__file__), 'operate_stock.csv')
    csv_path_output = os.path.join(os.path.dirname(__file__), 'completed_stock2.csv')
    field_index, result = read_csv_and_find_field(csv_path_input)

    for i in xrange(len(result)):
        name = result[i][field_index.get('name_new')]
        result[i][field_index.get('pinyin')] = create_pinyin(name)

    write_to_csv(csv_path_output, result)

